package cn.hpclub.server.util;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

import com.jfinal.core.JFinal;

import cn.hpclub.server.bean.SystemConfig;

public class UploadFileUtil{

    public static String  saveImage(File source){
        String imageDir = SystemConfigUtil.getSystemConfig().getUploadDir();
        String imageExtension = StringUtils.substringAfterLast(source.getName(), ".").toLowerCase();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String dateString = simpleDateFormat.format(new Date());
        String uuid = CommonUtil.getUUID();
        File file = null;
        String url = SystemConfig.UPLOAD_IMAGE_DIR + dateString + "/" + uuid + "."
                + imageExtension;
        if(StringUtils.isEmpty(imageDir)) {
            //save file to web root
            url = JFinal.me().getServletContext().getContextPath() + url;
            file = new File(JFinal.me().getServletContext().getRealPath(url));
        }else{
            //save file to config directory
            String uploadImagePath = imageDir + "/image/" + dateString + "/" + uuid + "."
                    + imageExtension;
            file = new File(uploadImagePath);
        }
        try{
            FileUtils.moveFile(source, file);
        }
        catch(IOException e){
            e.printStackTrace();
        }
        
        return url;
    }
    
    public static String  saveFile(File source){
        String fileDir = SystemConfigUtil.getSystemConfig().getUploadDir();
        String fileExtension = StringUtils.substringAfterLast(source.getName(), ".").toLowerCase();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String dateString = simpleDateFormat.format(new Date());
        File file = null;
        String tmpFileName = CommonUtil.getUUID();
        String url = SystemConfig.UPLOAD_FILE_DIR + dateString + "/" + tmpFileName + "."
                + fileExtension;
        if(StringUtils.isEmpty(fileDir)) {
            //save file to web root
            url = JFinal.me().getServletContext().getContextPath() + url;
            file = new File(JFinal.me().getServletContext().getRealPath(url));
        }else{
            //save file to config directory
            String uploadImagePath = fileDir + "/file/" + dateString + "/" + tmpFileName + "."
                    + fileExtension;
            file = new File(uploadImagePath);
        }
        try{
            FileUtils.moveFile(source, file);
        }
        catch(IOException e){
            e.printStackTrace();
        }
        
        return url;
    }
}
